package com.lancoo.edu.platform.operation.backupRestore.service.init;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.URLUtil;
import com.lancoo.edu.platform.operation.backupRestore.domain.po.BrServerSysInfo;
import com.lancoo.edu.platform.operation.backupRestore.service.po.BrServerSysInfoService;
import com.lancoo.edu.platform.operation.commons.domain.api.system.ProductInfo;
import com.lancoo.edu.platform.operation.commons.domain.api.system.ServerDatabaseIpInfo;
import com.lancoo.edu.platform.operation.commons.domain.api.system.ServerInfo;
import com.lancoo.edu.platform.operation.commons.service.api.YunBaseApiService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author lzh
 * @Date 2024/4/3 14:46
 * @description 系统对应服务器IP初始化业务处理
 */
@Service
@AllArgsConstructor
@Slf4j
public class BrServerSysInitService {

    private final BrServerSysInfoService brServerSysInfoService;
    private final YunBaseApiService yunBaseApiService;

    /**
     * 保存系统对应服务器Ip
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveServerSysIp_pre() {
        // 1、获取安装了的全部系统的内网地址
        List<ServerInfo> serverInfoList = yunBaseApiService.getInnerServerInfoList(null, null);
        if (CollectionUtil.isEmpty(serverInfoList)) {
            log.info("【定时更新系统对应服务器IP--未获取到基础平台内网表中地址列表】");
        }
        // 2、转换为map，并且整理为Ip。key：sysId_schoolId，value：ip
        Map<String, String> sysEduMapIp = serverInfoList.stream()
                .filter(serverInfo -> {
                    if (StringUtils.isBlank(serverInfo.getSubjectId())) {
                        return true;
                    }
                    // 只获取教育局带有教育局标签的
                    return StringUtils.contains(serverInfo.getSubjectId(), "E-");
                })
                .collect(Collectors.groupingBy(serverInfo -> StringUtils.isBlank(serverInfo.getSubjectId()) ? serverInfo.getSysId() : serverInfo.getSysId() + "_" + serverInfo.getSubjectId(),
                        Collectors.mapping(serverInfo -> URLUtil.url(serverInfo.getWebSvrAddr()).getHost(), Collectors.joining())));
        // 3、遍历
        List<BrServerSysInfo> brServerSysInfoList = buildBrServerSysInfoList(sysEduMapIp);
        // 4、保存
        brServerSysInfoService.remove(null);
        brServerSysInfoService.saveBatch(brServerSysInfoList);
    }

    /**
     * 保存系统对应服务器Ip
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveServerSysIp() {
        // 1、获取安装了的全部系统的内网地址
        List<ServerDatabaseIpInfo> serviceDatabaseIpInfoList = yunBaseApiService.getDatabaseIpInfoList(null, null);
        if (CollectionUtil.isEmpty(serviceDatabaseIpInfoList)) {
            log.info("【更新系统对应服务器IP--未获取到基础平台内网表中地址列表】");
        }
        // 2、转换为map，并且整理为Ip。key：sysId，value：ip
        // Map<String, String> sysSchoolMapIp = serviceDatabaseIpInfoList.stream()
        //         .collect(Collectors.toMap(ServerDatabaseIpInfo::getSysId, ServerDatabaseIpInfo::getDatabaseIp));
        Map<String, String> sysSchoolMapIp = serviceDatabaseIpInfoList.stream()
                .filter(Objects::nonNull) // 过滤掉null元素
                .collect(Collectors.toMap(
                        ServerDatabaseIpInfo::getSysId,
                        ServerDatabaseIpInfo::getDatabaseIp,
                        (existing, replacement) -> existing, // 解决键冲突问题
                        ConcurrentHashMap::new // 使用线程安全的ConcurrentHashMap
                ));
        // 3、遍历
        List<BrServerSysInfo> brServerSysInfoList = buildBrServerSysInfoList(sysSchoolMapIp);
        // 4、保存
        brServerSysInfoService.remove(null);
        boolean b = brServerSysInfoService.saveBatch(brServerSysInfoList);
    }

    /**
     * 构建系统对应服务器Ip信息列表
     *
     * @param sysEduMapIp 系统对应服务器Ip
     * @return 系统对应服务器Ip信息列表
     */
    private List<BrServerSysInfo> buildBrServerSysInfoList_pre(Map<String, String> sysEduMapIp) {
        List<BrServerSysInfo> brServerSysInfoList = new ArrayList<>();
        for (Map.Entry<String, String> entry : sysEduMapIp.entrySet()) {
            BrServerSysInfo brServerSysInfo = new BrServerSysInfo();
            String[] split = entry.getKey().split("_");
            brServerSysInfo.setSysId(split[0]);
            if (split.length > 1) {
                brServerSysInfo.setEduId(split[1]);
            }
            brServerSysInfo.setServerIp(entry.getValue());
            brServerSysInfoList.add(brServerSysInfo);
        }
        return brServerSysInfoList;
    }

    /**
     * 构建系统对应服务器Ip信息列表
     *
     * @param sysEduMapIp 系统对应服务器Ip
     * @return 系统对应服务器Ip信息列表
     */
    private List<BrServerSysInfo> buildBrServerSysInfoList(Map<String, String> sysEduMapIp) {
        ProductInfo productInfo = yunBaseApiService.getProductInfo();
        // 遍历赋值
        List<BrServerSysInfo> brServerSysInfoList = new ArrayList<>();
        for (Map.Entry<String, String> entry : sysEduMapIp.entrySet()) {
            BrServerSysInfo brServerSysInfo = new BrServerSysInfo();
            brServerSysInfo.setSysId(entry.getKey());
            brServerSysInfo.setServerIp(entry.getValue());
            brServerSysInfo.setEduId(Objects.nonNull(productInfo)&&StringUtils.isNotBlank(productInfo.getEduId())? productInfo.getEduId() : null);
            brServerSysInfoList.add(brServerSysInfo);
        }
        return brServerSysInfoList;
    }

}
